<?php

namespace app\admin\controller\daily;
use think\Db;
class Nuyunwangluo
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $akikey = 'key=weacb2c7cfcxd5c31a';

    public function index()
    {
        set_time_limit(0);
        //加入redis
//        $this->redis = new \Redis();
//        $this->redis->connect('127.0.0.1',6379);
//        if($this->redis->get('is_update')){
//            echo '该程序已经在执行，请等待~';
//            die;
//        }
//        $this->redis->set("is_update",1);
//        $expireTime = time()+3600;
//        $this->redis->expireAt('is_update', $expireTime);
        //查询本地游戏分类
        $game = DB::name("game")->select();
        $game_info = DB::name("game_info")->select();
        //获取用户分类
        $url_first = "https://www.nuyunwangluo.com/gshop/tripartite/catelist";

        $url1 = $url_first . '?sign=' . md5($this->akikey);
        $return = $this->GetHttp($url1);
        $data = $return->data;
        //返回参数格式：
//        [{
//            "name": "王者荣耀",
//            "arealist": [
//                {
//                    "name": "安卓QQ账号",
//                    "cate_id": 19
//                },
//                {
//                    "name": "安卓微信账号",
//                    "cate_id": 20
//                },
//                {
//                    "name": "苹果QQ账号",
//                    "cate_id": 21
//                },
//                {
//                    "name": "苹果微信账号",
//                    "cate_id": 22
//                }
//            ],
//            "image": "http://www.nuyunwangluo.com/upload/202103291015222516.png",
//            "cate_id": 8
//        },]
        foreach ($data as $key => $val) {
//            $params1 = array(
//                'cateid'=>$val->cate_id,
//                'page'=>1,
//                'pagesize'=>100
//            );
//            ksort($params1);


            //获取到首页游戏分类列表，根据分类来请求账号列表接口
            for ($i = 1; $i < 10; $i++) {
                $params1 = "cateid=" . $val->cate_id . "&page=" . $i . "&pagesize=1000";
                $url_second = "https://www.nuyunwangluo.com/gshop/tripartite/shoplist_qy?" . $params1 . "&sign=" . md5($params1 . "&" . $this->akikey);
                $return_data1 = $this->GetHttp($url_second);
                if (!$return_data1->data) {
                    break;
                }
                //获取账号详情
                foreach ($return_data1->data as $key1 => $val1) {
                    $insert = [];
                    //插入数据库
                    //查找本地游戏id
                    $gameName = $val1->catename;

//                //特殊处理（单个游戏进行处理）
//                switch ($gameName) {
//                    case '原神':
//                        $this->yuanshen_game($val1);
//                        break;
//                    default:
//                        break;
//                }

                    //添加平台
                    $gameName_id = 0;
                    foreach ($game as $gameKey => $gameVal) {
                        if ($gameVal['game'] == $gameName) {
                            $gameName_id = $gameVal['id'];
                            break;
                        }
                    }
                    if ($gameName_id == 0) {
                        //本地未找到游戏，加入日志，提示运维加入游戏
                        $this->writeLog("未找到游戏" . $gameName);
                        continue;
                    }
                    //查找本地游戏分类
                    $cateType = $val1->cate2name;
                    $gameInfoArr = array();
                    foreach ($game_info as $gameinfoValue) {
                        if ($gameinfoValue['game_id'] == $gameName_id) {
                            $gameInfoArr[] = $gameinfoValue;
                        }
                    }
                    //再判断是QQ还是微信
                    $gameInfoArr_fenlei1 = array();
                    foreach ($gameInfoArr as $gameInfoArr_val) {
                        if ($gameInfoArr_val['gt_id'] == 1) {
                            $gameInfoArr_fenlei1[] = $gameInfoArr_val;
                        }
                    }
                    $gameInfoArr_fenlei2 = array();
                    foreach ($gameInfoArr as $gameInfoArr_val) {
                        if ($gameInfoArr_val['gt_id'] == 2) {
                            $gameInfoArr_fenlei2[] = $gameInfoArr_val;
                        }
                    }
                    $gameInfoArr_fenlei3 = array();
                    foreach ($gameInfoArr as $gameInfoArr_val) {
                        if ($gameInfoArr_val['gt_id'] == 3) {
                            $gameInfoArr_fenlei3[] = $gameInfoArr_val;
                        }
                    }
                    $gameInfoArr_fenlei4 = array();
                    foreach ($gameInfoArr as $gameInfoArr_val) {
                        if ($gameInfoArr_val['gt_id'] == 4) {
                            $gameInfoArr_fenlei4[] = $gameInfoArr_val;
                        }
                    }
                    $gameInfoArr_fenlei5 = array();
                    foreach ($gameInfoArr as $gameInfoArr_val) {
                        if ($gameInfoArr_val['gt_id'] == 5) {
                            $gameInfoArr_fenlei5[] = $gameInfoArr_val;
                        }
                    }
                    //判断平台 (安卓、苹果)
                    if (preg_match('/安卓/', $cateType)) {
                        foreach ($gameInfoArr_fenlei1 as $fenlei_val) {
                            if (preg_match('/安卓/', $fenlei_val['name'])) {
                                $insert['plat_id'] = $fenlei_val['id'];
                            }
                        }

                        if (preg_match('/QQ/', $cateType)) {
                            foreach ($gameInfoArr_fenlei2 as $fenlei_val) {
                                if (preg_match('/QQ/', $fenlei_val['name'])) {
                                    $insert['operator_id'] = $fenlei_val['id'];
                                    $insert['operator'] = $fenlei_val['name'];
                                    $insert['area']=$cateType;
                                    $insert['server']='全服';
                                }
                            }
                        } else if (preg_match('/微信/', $cateType)) {
                            foreach ($gameInfoArr_fenlei2 as $fenlei_val) {
                                if (preg_match('/微信/', $fenlei_val['name'])) {
                                    $insert['operator_id'] = $fenlei_val['id'];
                                    $insert['operator'] = $fenlei_val['name'];
                                    $insert['area']=$cateType;
                                    $insert['server']='全服';
                                }
                            }
                        }

                    } else if (preg_match('/苹果/', $cateType)) {
                        foreach ($gameInfoArr_fenlei1 as $fenlei_val) {
                            if (preg_match('/苹果/', $fenlei_val['name'])) {
                                $insert['plat_id'] = $fenlei_val['id'];
                            }
                        }
                        if (preg_match('/QQ/', $cateType)) {
                            foreach ($gameInfoArr_fenlei2 as $fenlei_val) {
                                if (preg_match('/QQ/', $fenlei_val['name'])) {
                                    $insert['operator_id'] = $fenlei_val['id'];
                                    $insert['operator'] = $fenlei_val['name'];
                                    $insert['area']=$cateType;
                                    $insert['server']='全服';
                                }
                            }
                        } else if (preg_match('/微信/', $cateType)) {
                            foreach ($gameInfoArr_fenlei2 as $fenlei_val) {
                                if (preg_match('/微信/', $fenlei_val['name'])) {
                                    $insert['operator_id'] = $fenlei_val['id'];
                                    $insert['operator'] = $fenlei_val['name'];
                                    $insert['area']=$cateType;
                                    $insert['server']='全服';
                                }
                            }
                        }
                    } else if (preg_match('/官服/', $cateType)) {
                        if ($gameInfoArr_fenlei1) {
                            foreach ($gameInfoArr_fenlei1 as $fenlei_val) {
                                if (preg_match('/双平台互通/', $fenlei_val['name'])) {
                                    $insert['plat_id'] = $fenlei_val['id'];
                                }
                            }
                        } else {
                            foreach ($gameInfoArr_fenlei4 as $fenlei_val) {
                                if (preg_match('/官方/', $fenlei_val['name'])) {
                                    $insert['area_id'] = $fenlei_val['id'];
                                    $insert['area'] = $fenlei_val['name'];
                                }
                            }
                        }

                    } else if (preg_match('/电信/', $cateType)) {
                        foreach ($gameInfoArr_fenlei4 as $fenlei_val) {
                            if (preg_match('/电信/', $fenlei_val['name'])) {
                                $insert['server_id'] = $fenlei_val['id'];
                                $insert['server'] = $fenlei_val['name'];
                            }
                        }
                    } else if (preg_match('/联通/', $cateType)) {
                        foreach ($gameInfoArr_fenlei4 as $fenlei_val) {
                            if (preg_match('/联通/', $fenlei_val['name'])) {
                                $insert['server_id'] = $fenlei_val['id'];
                                $insert['server'] = $fenlei_val['name'];
                            }
                        }
                    } else if (preg_match('/Steam/', $cateType)) {
                        if ($gameInfoArr_fenlei1) {
                            foreach ($gameInfoArr_fenlei4 as $fenlei_val) {
                                if (preg_match('/steam/', $fenlei_val['name'])) {
                                    $insert['plat_id'] = $fenlei_val['id'];
                                }
                            }
                        } else {
                            foreach ($gameInfoArr_fenlei4 as $fenlei_val) {
                                if (preg_match('/steam/', $fenlei_val['name'])) {
                                    $insert['area_id'] = $fenlei_val['id'];
                                    $insert['area'] = $fenlei_val['name'];
                                }
                            }
                        }

                    } else {
                        $insert['plat_id'] = 0;
                        foreach ($gameInfoArr_fenlei1 as $fenlei_val) {
                            if (preg_match('/' . $cateType . '/', $fenlei_val['name'])) {
                                $insert['plat_id'] = $fenlei_val['id'];
                            }
                        }
                    }
                    //判断表中是否存在
                    $res = DB::name("nuyunwangluo_data")->where("shop_id", $val1->shop_id)->find();
                    $insert['game_id'] = $gameName_id;
                    $insert['plat'] = $cateType;
                    $insert['shop_id'] = $val1->shop_id;
                    $insert['logo'] = $val1->logo;
                    $insert['cate_id'] = $val1->cate_id;
                    $insert['catename'] = $val1->catename;
                    $insert['cate_id2'] = $val1->cate_id2;
                    $insert['cate2name'] = $val1->cate2name;
                    $insert['title'] = $val1->title;
                    $insert['money'] = $val1->money;
                    $insert['type'] = $val1->type;
                    $insert['create_time'] = $val1->createtime;
                    $insert['created_time'] = date("Y-m-d H:i:s", time());
                    if ($res) {
                        //下架商品
                        continue;
                    } else {
                        //添加详情
                        $params2 = "shop_id=" . $val1->shop_id;
                        $url_third = "https://www.nuyunwangluo.com/gshop/tripartite/shopinfo?" . $params2 . "&sign=" . md5($params2 . "&" . $this->akikey);
                        $return_data2 = $this->GetHttp($url_third);
                        if(!empty($return_data2->data)){
                            $insert['attribute'] = $return_data2->data->shopinfo->attribute;
                            $insert['text'] = $return_data2->data->shopinfo->text;
                            $imgs = $return_data2->data->image;
                            $imgs_arr = array_column($imgs,'image');
                            $insert['image']=implode(",",$imgs_arr);
                        }
                        DB::name("nuyunwangluo_data")->insert($insert);
                    }
                }

            }
        }
        $this->addgoodList();
        echo '执行成功！';
        $this->redis->set("is_update",0);
        die;

    }

    /**
     * get
     * @param string $url 请求地址
     */
    function GetHttp($url)
    {
        // 关闭句柄
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 0);   //只需要设置一个秒的数量就可以
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl); //返回api的json对象
        if (curl_exec($curl) === false) {
            return 'Curl error: ' . curl_error($curl);
        }
        //关闭URL请求
        curl_close($curl);
        return json_decode($tmpInfo); //返回json对象
    }

    function writeLog($content)
    {
        $file = 'nuyunwangluo.log';
        // 这个函数支持版本(PHP 5)
        if ($f = file_put_contents($file, $content.'\r\n', FILE_APPEND)) {
            //echo "成功。<br />";
        }

    }

    //同步到商品表中
    public function addgoodList()
    {
        $list = DB::name("nuyunwangluo_data")->where(['type'=>1,'is_publish'=>1])->select();
        $game_info5 = DB::name("game_info")->where(['gt_id'=>5,'name'=>'账号'])->select();
        $fee_base = DB::name("server")->where(['game_id'=>0,'safe'=>1,'method'=>1])->find();
        $fee_list = DB::name("server")->where(['game_id'=>['<>',0],'safe'=>1,'method'=>1])->select();
        try {
            Db::startTrans();
            foreach($list as $key=>$val){
                $image_arr = explode(',',$val['image']);
                $data['goods_class_type'] = 1;
                $id = '76';
                $rand = $id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
                $sn = date('Yhis') . $rand;
                $id = str_pad($id, (18 - strlen($sn)), '0', STR_PAD_BOTH);
                $order_sn = $sn . $id;
                $data['goods_sn'] = $order_sn;
                $data['uid'] = '76';
                $data['gameid']=$val['game_id'];
                $data['gamename']=$val['catename'];
                $data['title'] = "【".$val['shop_id']."】".mb_substr($val['title'],0,235);
                $data['image'] = $image_arr[0];
                $data['images'] = $val['image'];
                foreach($game_info5 as $vv){
                    if($vv['game_id']==$val['game_id']){
                        $data['goods_type']=$vv['id'];
                        $data['type_name']=$vv['name'];
                    }
                }
                $data['prices']=$val['money'];
                //查询费率
                /*$fee = 0;
                if($fee_list){
                    foreach($fee_list as $vv){
                        if($vv['game_id'] == $val['game_id']){
                            $fee = $vv['service'];
                        }
                    }
                }else{
                    $fee = $fee_base['service'];
                }*/
				$fee = 0.15;
                $data['price'] = $val['money']*(1+$fee);
                $data['plat_id']=$val['plat_id'];
                $data['plat']=$val['plat'];
                $data['operator']=$val['operator'];
                $data['operator_id']=$val['operator_id'];
                $data['area_id']=$val['area_id'];
                $data['area']=$val['area'];
                $data['server']=$val['server'];
                $data['server_id']=$val['server_id'];
                $data['info']=$val['text'];
                $data['havetime'] = time() + 86400*30; //默认30天
                $data['g_account'] = '';
                $data['g_password'] = '';
                $data['jy_time'] = '3:00-21:00';
//            $data['yd_id'] = '';
                $data['is_warrant'] = 2;
                $data['is_appoint'] = 2;
//            $data['cipher'] = '';
                $data['is_safe'] = 1;
                $data['is_pei'] = 2;
                $data['stock'] = 1;
                $data['mobile'] = '18052134564';
                $data['qq']='130221011';
                $data['status'] = 1;
                $data['createtime'] = time();
                $res = DB::name("goods")->insertGetID($data);
                if($res){
                    DB::name("nuyunwangluo_data")->where('id',$val['id'])->update(['is_publish'=>2,'order_no'=>$order_sn]);
                }
            }
            // 提交事务
            Db::commit();
            echo '执行成功';
            //throw new Exception('操作成功');
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            //注意：我们做了回滚处理
            $this->error($e->getMessage());
        }

    }

    //获取游戏总分类
    public function getGameType(){
        //获取用户分类
        $url_first = "https://www.nuyunwangluo.com/gshop/tripartite/catelist";

        $url1 = $url_first . '?sign=' . md5($this->akikey);
        $return = $this->GetHttp($url1);
        dump($return);die;
    }

    /**
     * 获取游戏详情
     * param：cate_id 分类id
     */
    public function getSubGame(){
        $params1 = "cateid=8&page=1&pagesize=1000";
        $url_second = "https://www.nuyunwangluo.com/gshop/tripartite/shoplist_qy?" . $params1 . "&sign=" . md5($params1 . "&" . $this->akikey);
        $return_data = $this->GetHttp($url_second);
        dump($return_data);die;
    }

    public function updateShopId(){
        $list = DB::name("goods")->where(['mobile'=>'18052134564','id'=>['>','1000']])->select();
        foreach($list as $val){
            $info = DB::name("nuyunwangluo_data")->where(['image'=>['like',"%".$val['image']."%"]])->find();
            $title = "【".$info['shop_id']."】".mb_substr($val['title'],0,230);
            DB::name("goods")->where('id',$val['id'])->update(['title'=>$title]);
        }
        echo '执行成功！';
        die;
    }

    public function downGoods(){
        $list = DB::name("nuyunwangluo_data")->group("cate_id")->field("cate_id")->select();
        $cate_arr = array_column($list,'cate_id');
        //获取所有下架商品(最新的五千数据)
//        foreach($cate_arr as $val){
            $params1 = "cateid=10&page=1&pagesize=5000";
            $url_second = "https://www.nuyunwangluo.com/gshop/tripartite/shoplistlower_qy?" . $params1 . "&sign=" . md5($params1 . "&" . $this->akikey);
            $return_data3 = $this->GetHttp($url_second);
//            if (!$return_data3->data) {
//                break;
//            }
            $downgoods = array();
            array_push($downgoods,array_column($return_data3->data,'shop_id'));
            dump($downgoods);die;
            $data = DB::name("nuyunwangluo_data")->where(['cate_id'=>$val,'is_publish'=>1])->select();
            foreach($data as $vv){
                if(in_array($vv['shop_id'],$downgoods[0])){
                    DB::name("nuyunwangluo_data")->where('id',$vv['id'])->update(['type'=>2]);
//                    DB::name("goods")->where(['goods_sn'=>$vv['order_no'],'uid'=>76,'mobile'=>'18052134564'])->update(['status'=>2]);
                }
            }

//        }
        echo 'success';die;
    }
}